package com.zz.ui_demo_wedgit;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ProgressBarctivity extends AppCompatActivity {
    private int progress = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_barctivity);
        //进度条
        ProgressBar pb3 = findViewById(R.id.pb_3);
        Button btnAdd = findViewById(R.id.btn_add);
        //手动增加进度条
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int current = pb3.getProgress();//获取当前的进度值
                int max = pb3.getMax();
                if(current < max){
                    pb3.setProgress(current + 10);
                }else{
                    btnAdd.setEnabled(false);//否则不继续增加
                }
            }
        });
        //利用线程自动增加进度条
        ProgressBar pb4 = findViewById(R.id.pb_4);
        Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                if(msg.what == 1){//表示可以更新
                    pb4.setProgress(progress);
                }else{
                    Toast.makeText(ProgressBarctivity.this, "加载完成",Toast.LENGTH_SHORT).show();
                    pb4.setVisibility(View.GONE);
                }
                return true;
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    progress += Math.random() + 10;
                    try{
                        Thread.sleep(500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    if(progress<= 100){
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }else{
                        msg.what = -1;
                        handler.sendMessage(msg);
                        break;
                    }
                }
            }
        }).start();
    }
}